<?php
class Study {
	private $message = "";
	private $studType = 'CLUSTERSTUDY';
	private $clusterParam = null;
	private $auth = null;
	private $cm = null;
	function Study() {
		$this->clusterParam = new ClusterParam();
		$this->auth = new Authority();
		require_once (ROOT_PATH . "Lib/Mode/ClusterManager.class.php");
		$this->cm = new ClusterManager();
	}

	public function run() {
		preg_match('/^@(\S+)\s*(.*)$/is', trim($_POST[Message]), $m);
		if ($m[1] == "学习") {
			$this->auth = new Authority(true);
			if($this->auth->adminLevel<5) {
				if(strrpos($_POST[Message],"[@:0:")>0) {
					$this->message = "你无权学习此命令~~";
					return;
				}
			}
			if($this->cm->study == 0) {
			$this->message = "本群学习模式还未开启,请管理员 @study 开启0(>_<)0";
			return;
		}
			$this->clusterStudy();
		} else
			if ($m[1] == "忘记") {
				$this->auth = new Authority(true);
				$this->forgetStudy();
			} else if($m[1] == "回忆") {
				$this->memoryStudy();
				
			}

	}

	private function clusterStudy() {

		$_POST[Message] = stripcslashes($_POST[Message]);
		$p = '/@学习[\s]+(-[eps])?(.+?)[^@]回答(.+)/si';
		preg_match($p, trim($_POST[Message]), $d);
		$is_exec = $d[1] == "-e" ? 1 : 0;
		$scope = 0;
		$study_tbname = "td_study";
		$ty = "";
		if ($d[1] == "-p" ) {
			$ty = "-p";
			if($this->auth->adminLevel <4) {
				$this->message = "该功能已经关闭~";
				return ;
			}
			$study_tbname = "td_p_study";
		}

		if ($d[1] == "-s") {
			$scope = 1;
		}
		$priority = 1;
		if ($this->auth->adminLevel > 4) {
			$priority = 10;
		}
		$arr = array (
			'id' => 0,
			'question' => trim($d[2]),
			'qq' => $_POST[Sender],
			'answer' => trim($d[3]),
			'ClusterNum' => $_POST[ClusterNum],
			'is_exec' => $is_exec,
			'nick' => $_POST[Nick],
			'scope' => $scope,
			'priority'=>$priority,
			'update_time'=>date("Y-m-d H:i:s", (time() + 8 * 3600))
		);

		if ($d[2] && $d[3] && trim($d[2]) != "") {
			//echo substr(trim($d[1]),0,1)."asas";
			$ret2 = @ DB :: GetQueryResult("select * from {$study_tbname} where flag =1 and qq='{$_POST[Sender]}' and question='{$arr[question]}'  and scope={$scope} ", true); //配置参数初始化
			if ($ret2 && $this->auth->adminLevel < 3) {
				$this->message = "咦！{$_POST[Nick]}! 你明明都教过我这个的啦，难到你认为我很笨吗？>_<";
				return;
			}
			//过滤词汇
			$filter_word_arr = array ();
			if ($this->auth->adminLevel < 5)
				$filter_word_arr = require (ROOT_PATH . 'Common/keyword.php');
			$filterarr = array (
				"!",
				"@",
				"#",
				"$",
				"%",
				"^",
				"&",
				"*",
				"(",
				")",
				".",
				"-",
				"+",
				"=",
				"ˇ",
				"¨",
				"·",
				"/",
				"\\",
				"_",
				"<",
				">",
				"?",
				"{",
				"}",
				"[",
				"]",
				"|",
				",",
				"　",
				" ",
				" ",
				"。",
				"；",
				"：",
				"？",
				"，",
				";",
				":",
				"'",
				"\"",
				"~",
				"`"
			);
			foreach ($filter_word_arr as $v) {

				if (@ strpos("yaya" . str_replace($filterarr, "", $arr[answer] . $arr[question]), $v)) {
					$_SESSION['STUDY_ERR_NUM'] = isset ($_SESSION['STUDY_ERR_NUM']) ? ($_SESSION['STUDY_ERR_NUM'] + 1) : 1;
					if ($_SESSION['STUDY_ERR_NUM'] == 1) {
						$this->message = "咦？{$_POST[Nick]}！请不要教我奇怪的东西啦，再教的话，我这几天都不会理你啦>_<~!";
					} else {
						$this->message = "哼！{$_POST[Nick]}！真的不理你啦>_<~!";
						$ret = @ DB :: GetQueryResult("select * from td_blacklist where qq='{$_POST[Sender]}' and flag=1 and clusternum='0'", true);
						$start_time = date("YmdHis", (time() + 8 * 3600));
						$end_time = date("Ymd", (time() + (48 + 8) * 3600)) . "235959";
						if ($ret) {
							@ DB :: Query("update  td_blacklist set start_time ='{$start_time}', end_time='{$end_time}',day=3,keword='{$v}' where flag=1 and qq='{$_POST[Sender]}' and clusternum='0'");

						} else {
							$arr = array (
								'qq' => $_POST[Sender],
								'clusternum' => '0',
								'start_time' => $start_time,
								'end_time' => $end_time,
								'day' => 3,
								'keword' => $v
							);
							DB :: SaveTableRow('td_blacklist', $arr);
						}

						session_destroy();
					}
					return;
				}
			}
			
			/*$ret = @ DB :: GetQueryResult("select * from td_normal_user_info where qq='{$_POST[Sender]}' ", true);
			if($ret||true) {
				if($ret[first_study]) {
					if($ret[first_study]== date("Y-m-d", time() + 8 * 3600)) {
						if( $ret[study_time]<=0) {
							$this->message = "嗯,今天已经学得够多了，明天在教我吧~~";
							return;
						}
					} else {
						$first_study = date("Y-m-d", time() + 8 * 3600);
						@ DB :: Query("update td_normal_user_info set `study_time`=10,`first_study`='{$first_study}' where qq={$_POST[Sender]} ");
					}
					
				} else {
						$first_study = date("Y-m-d", time() + 8 * 3600);
					    @ DB :: Query("update td_normal_user_info set `first_study`='{$first_study}' where qq={$_POST[Sender]} ");
				}
				
    				    @ DB :: Query("update td_normal_user_info set `study_time`=study_time-1  where qq={$_POST[Sender]} ");
			}else{
				$this->message = "非法用户~";
				return ;
			}*/
			if ($qid = DB :: SaveTableRow($study_tbname, $arr)) {
				DB::Query("update ".$study_tbname." set nick='{$_POST[Nick]}' where qq='{$_POST[Sender]}' and  nick is null ") ;
				$this->message = $this->clusterParam->getParamValue('STUDY_SUCCESS_MESS');
				$sendM = "{$_POST[Nick]}({$_POST[Sender]}):在群[{$_POST[ClusterName]}({$_POST[ClusterNum]})]中\n学习了：{$arr[question]}\n回答：{$arr[answer]}";
				$sendM.="\n删除请执行：@delete {$ty} {$qid}";
				
				$api = new Api("SendClusterMessage");
				$api->doApi('141096720',$sendM);
			} else {
				$this->message = "学不会~！";
			}

		} else {
			$this->message = "八嘎，貌似参数有些问题，好好看清楚！";
		}
	}

	/**
	 * 查找词库
	 */
	function getStudyAnswer() {
		
		//先搜索通用词库
		$p = "/(^索妮娅酱)|(^索妮娅)/";
		$mess1 = trim( $_POST[Message]);
 		$mess2 = preg_replace($p, '',trim( $_POST[Message]));
 		if($mess1!=$mess2 && $mess2!="") {
 			$sql = "select * from td_study where flag =1 and (question ='{$mess1}' or question ='{$mess2}')";
 		} else { 
			$sql = "select * from td_study where flag =1 and question ='" . trim($_POST[Message]) . "'";
 		}
		$ret = DB :: GetQueryResult($sql, false);
		$cou = count($ret);
		
		if (($cou != 0) && ($this->auth->adminLevel > 3 || $this->cm->respond == 1)) {
			$admin_arr = null;
			$my_arr_exec = null;
			$my_arr = null;
			$other_arr = null;
			$cluster_arr =null;
			$i = 0;
			$j = 0;
			$k = 0;
			$l = 0;
			$z = 0;
			foreach ($ret as $key => $s) {
				$is_time = true;
				if ($s[start_time] != 0 || $s[end_time] != 0 || $s[start_date] != 0 || $s[end_date] != 0) {
					$date = date("Ymd", time() + 8 * 3600);
					$time = date("His", time() + 8 * 3600);
//					myEcho($date);
//					myEcho($time);
//					myEcho($s[start_date]);
//					myEcho($s[start_time]);
//					myEcho($s[end_date]);
//					myEcho($s[end_time]);
					
					if ($s[start_date] != 0 && $s[end_date] != 0 && $s[start_time] != 0 && $s[end_time] != 0) {
						if ($s[start_date] <= $date && $s[end_date] >= $date && $s[start_time] <= $time && $time <= $s[end_time]) {
							$is_time = true;
						} else {
							$is_time = false;
						}
					} else
						if ($s[start_date] == 0 && $s[end_date] == 0 && $s[start_time] != 0 && $s[end_time] != 0) {
							if ($s[start_time] <= $time && $time <= $s[end_time]) {
								$is_time = true;
							} else {
								$is_time = false;
							}

						} else
							if ($s[start_date] != 0 && $s[end_date] != 0 && $s[start_time] == 0 && $s[end_time] == 0) {
								if ($s[start_date] <= $date && $s[end_date] >= $date) {
									$is_time = true;
								} else {
									$is_time = false;
								}

							} else {
								if ($s[start_time] <= $time && $time <= $s[end_time]) {
								$is_time = true;
								} else {
								$is_time = false;
								}
							}

				}
				if ($is_time && (($s[qq] == $_POST[Sender])) && ($s[is_exec] == 1)) {
					$my_arr_exec[$l++] = $s;
					break;

				}

				if ($is_time && ($s[priority] == 10) && ($s[is_exec] == 0)) {

					if ($s[scope] == 0) {
						$admin_arr[$i++] = $s;
					} else {
						if ($s[qq] != $_POST[Sender])
							$admin_arr[$i++] = $s;
					}
					continue;
				}

				if ($is_time && ($this->auth->adminLevel > 2 || ($s[qq] == $_POST[Sender])) && ($s[is_exec] == 0) && $s[scope] == 0) {
					$my_arr[$j++] = $s;
					continue;
				}

				if ($is_time && ($this->auth->adminLevel > 2 || $s[clusternum] == $_POST[ClusterNum]) && ($s[is_exec] == 0)) {
					$cluster_arr[$k++] = $s;
					continue;
				}
				if ($is_time && ($this->auth->adminLevel > 3 || $this->cm->match == 1) && ($s[clusternum] != $_POST[ClusterNum]) && ($s[is_exec] == 0)) {
					$other_arr[$z++] = $s;
					continue;
				}
			}

			$arr = null;
			if ($my_arr_exec) {

				if (@preg_match('/\{(@[^}]+)\}/is', $my_arr_exec[0][answer], $m)) {
					$_POST[Message] = $m[1];
					require_once (ROOT_PATH . "Lib/Event/ReceiveClusterIM.class.php");
					$event = new ReceiveClusterIM;
					$event->run();
					$mess = $event->message;
					$this->message = str_replace($m[0], $mess, $my_arr_exec[0][answer]);
				} else {
					$this->message = $my_arr_exec[0][answer];
				}
			} else {
				if ($other_arr)
					$arr = $other_arr;
				if ($cluster_arr)
					$arr = $cluster_arr;
				if ($my_arr)
					$arr = $my_arr;
				if ($admin_arr)
					$arr = $admin_arr;

				$index = rand(0, count($arr) - 1);
				Favorable :: clusterFavReward(3);
				Favorable::updateUserInfo(2);
				if (@preg_match('/\{(@[^}]+)\}/is', $arr[$index][answer], $m)) {
					$_POST[Message] = $m[1];
					require_once (ROOT_PATH . "Lib/Event/ReceiveClusterIM.class.php");
					$event = new ReceiveClusterIM;
					$event->run();
					$mess = $event->message;
					$this->message = str_replace($m[0], $mess, $arr[$index][answer]);
				} else {
					$this->message = $arr[$index][answer];
				}
				//$this->message = $arr[$index][answer];
				$_SESSION['NOW_MESS_ID'] = $arr[$index][id];
			}
		} else {
			
			//关键词库查找
			$my_ret = @DB :: GetQueryResult("select * from td_p_study where (ClusterNum='{$_POST[ClusterNum]}'  or  priority='10')  and flag=1", false);
			if (count($my_ret) != 0) {
				
				foreach ($my_ret as $v) {
					$p = '/' . $v[question] . '/is';
					
					// preg_match($p, $_POST[Message], $m);
					//print_r($m);
					if (@ preg_match($p, $_POST[Message], $m)) {
					
						$answer = preg_replace(array (
							"/<1>/",
							"/<2>/",
							"/<3>/"
						), array (
							$m[1],
							$m[2],
							$m[3]
						), $v[answer]);
						$this->message = $answer;
						
						if (preg_match('/\{(@[^}]+)\}/is', $answer, $n)) {
						
							$_POST[Message] = $n[1];
							require_once (ROOT_PATH . "Lib/Event/ReceiveClusterIM.class.php");
							$event = new ReceiveClusterIM;
							$event->run();
							$mess = $event->message;
							Favorable :: clusterFavReward(5);
							Favorable::updateUserInfo(3);
							$this->message = str_replace($n[0], $mess, $answer);
							
						}
						
					}
				}

			}
			if($this->message && $this->message !="") {
				return;
			}
			if ($this->cm->math == 1) { //数学表达式计算
				$p = '/[0-9\+\-\*\/\(\)=]+/';
				//return;
				if (preg_match($p, $_POST[Message], $m)) {

					$this->message = math($_POST[Message]);
				}

			}
		}
	}

	private function forgetStudy() {
		$p = '/@忘记[\s]+(-p)*(.*?)(->)(.*)/is';
		if (!preg_match($p, $_POST[Message], $m)) {
			preg_match('/@忘记[\s]+(-p)*(.*)/is', $_POST[Message], $m);
		}

		$tableName = "td_study";
		if ($m[1]) {
			$tableName = "td_p_study";
		}
		$word = trim($m[2]);
		$an = "";
		if ($m[3]) {
			$an = " and answer='" . trim($m[4]) . "' ";
		}

		$sql = "";
		$sql2 = "";
		if (!($this->auth->adminLevel > 0)) {
			if ($this->auth->isClusterAdmin > 0) {
				$sql = "update {$tableName} set flag = 0 where question ='{$word}' and ClusterNum='{$_POST[ClusterNum]}' {$an} and priority<>10";
				$sql2 = "select * from {$tableName} where question ='{$word}' and ClusterNum='{$_POST[ClusterNum]}' {$an} and flag = 1 and priority<>10";
			} else {
				$sql = "update {$tableName} set flag = 0 where question ='{$word}' and qq='{$_POST[Sender]}' {$an} and priority<>10";
				$sql2 = "select * from {$tableName} where question ='{$word}' and qq='{$_POST[Sender]}' {$an} and flag = 1  and priority<>10";
			}
		} else {
			if($this->auth->adminLevel > 4) {
				$sql = "update {$tableName} set flag = 0 where question ='{$word}' {$an} ";
				$sql2 = "select * from {$tableName} where question ='{$word}'  {$an} and flag = 1";
			}else {
				
				$sql = "update {$tableName} set flag = 0 where question ='{$word}' {$an} and priority<>10";
				$sql2 = "select * from {$tableName} where question ='{$word}'  {$an} and flag = 1 and priority<>10";
				//echo $sql2;
			}
				
				
			

		}
		//echo $sql;
		//echo $sql2;
		//  exit;
		if (!($ret = DB :: GetQueryResult($sql2, false))) {
			$this->message = ("你确定教过我这个吗？");
			return;
		}

		DB :: Query($sql);

		$this->message = $this->clusterParam->getParamValue('FORGET_STUDY_MESS');

	}
	
	private function memoryStudy() {
		$p = '/@回忆[\s]+(.*)/is';
		preg_match($p, $_POST[Message], $m);
	}
	
	private function __get($property_name) {
		return $this-> $property_name;
	}

	private function __set($property_name, $value) {
		$this->$property_name = $value;
	}
}
?>